package org.jeecg.modules.wangyue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wangyue.constant.CapitalFlowTypeConstant;
import org.jeecg.modules.wangyue.constant.DelFlagConstant;
import org.jeecg.modules.wangyue.constant.WithdrawalReviewConstant;
import org.jeecg.modules.wangyue.entity.CapitalFlow;
import org.jeecg.modules.wangyue.entity.UserBasic;
import org.jeecg.modules.wangyue.entity.UserRoleInfo;
import org.jeecg.modules.wangyue.entity.WithdrawalReview;
import org.jeecg.modules.wangyue.mapper.CapitalFlowMapper;
import org.jeecg.modules.wangyue.mapper.UserBasicMapper;
import org.jeecg.modules.wangyue.mapper.UserRoleInfoMapper;
import org.jeecg.modules.wangyue.mapper.WithdrawalReviewMapper;
import org.jeecg.modules.wangyue.model.req.ReqUserRoleInfoModel;
import org.jeecg.modules.wangyue.service.IWithdrawalReviewService;
import org.jeecg.modules.wangyue.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @Description: 提现审核表
 * @Author: jeecg-boot
 * @Date:   2023-06-30
 * @Version: V1.0
 */
@Service
public class WithdrawalReviewServiceImpl extends ServiceImpl<WithdrawalReviewMapper, WithdrawalReview> implements IWithdrawalReviewService {

    @Autowired
    private WithdrawalReviewMapper withdrawalReviewMapper;
    @Autowired
    private UserRoleInfoMapper userRoleInfoMapper;
    @Autowired
    private UserBasicMapper userBasicMapper;
    @Autowired
    private CapitalFlowMapper capitalFlowMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> userWithdrawal(ReqUserRoleInfoModel reqUserRoleInfoModel) {
        String userId = reqUserRoleInfoModel.getUserId();
        String userType = reqUserRoleInfoModel.getUserType();
        String amountStr = reqUserRoleInfoModel.getAmount();
        if(oConvertUtils.isEmpty(userId) || oConvertUtils.isEmpty(userType) || oConvertUtils.isEmpty(amountStr)){
            return Result.error("必输项不能为空");
        }
        //1.扣除用户余额
        //查询用户余额(行上锁)
        UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(userId, userType);
        UpdateWrapper<UserRoleInfo> userRoleInfoUpdateWrapper = new UpdateWrapper<>();
        userRoleInfoUpdateWrapper.eq("user_id", userId);
        userRoleInfoUpdateWrapper.eq("user_type", userType);
        userRoleInfoUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
        BigDecimal amount = new BigDecimal(amountStr);
        if(userRoleInfo.getBalance().compareTo(amount) == -1){
            return Result.error("余额不足！");
        }
        userRoleInfoUpdateWrapper.set("balance", userRoleInfo.getBalance().subtract(amount)); //扣掉余额
        userRoleInfoUpdateWrapper.set("total_amount", userRoleInfo.getTotalAmount().subtract(amount)); //扣掉总金额
        userRoleInfoUpdateWrapper.set("update_time", DateUtil.getTime("yyyy-MM-dd HH:mm:ss"));
        int userRoleInfoNum = userRoleInfoMapper.update(null, userRoleInfoUpdateWrapper);
        if(userRoleInfoNum < 1){
            return Result.error("提现失败(1)!");
        }

        //2.新增资金流水表记录
        //查询账号
        UserBasic userBasic =userBasicMapper.selectById(userRoleInfo.getUserId());
        CapitalFlow capitalFlow = new CapitalFlow();
        capitalFlow.setUserId(userRoleInfo.getUserId());
        capitalFlow.setAccount(userBasic.getAccount());
        capitalFlow.setUserType(userRoleInfo.getUserType());
        capitalFlow.setChangeType(CapitalFlowTypeConstant.withdrawal); //3-提现
        capitalFlow.setChangeName(CapitalFlowTypeConstant.withdrawalName); //提现
        capitalFlow.setBeforeChangeAmount(userRoleInfo.getBalance());
        capitalFlow.setChangeAmount(amount.negate());
        capitalFlow.setAfterChangeAmount(userRoleInfo.getBalance().subtract(amount));
        capitalFlow.setUpOrDown(CapitalFlowTypeConstant.money_down);
        int capitalFlowNum = capitalFlowMapper.insert(capitalFlow);
        if(capitalFlowNum < 1){
            throw new RuntimeException("提现失败(2)!");
        }
        return Result.OK("提现成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> jsApplyForWithdrawal(WithdrawalReview withdrawalReview) {
        //1.先查看提现金额是否充足(行上锁)
        UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(withdrawalReview.getUserId(), withdrawalReview.getUserType());
        if(userRoleInfo.getBalance().compareTo(withdrawalReview.getWithdrawalAmount()) == -1){
            return Result.error("余额不足,提现申请失败！");
        }

        //2.如果金额充足，则扣掉金额
        UpdateWrapper<UserRoleInfo> userRoleInfoUpdateWrapper = new UpdateWrapper<>();
        userRoleInfoUpdateWrapper.eq("user_id", withdrawalReview.getUserId());
        userRoleInfoUpdateWrapper.eq("user_type", withdrawalReview.getUserType());
        userRoleInfoUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
        userRoleInfoUpdateWrapper.set("balance", userRoleInfo.getBalance().subtract(withdrawalReview.getWithdrawalAmount())); //扣掉余额
        userRoleInfoUpdateWrapper.set("total_amount", userRoleInfo.getTotalAmount().subtract(withdrawalReview.getWithdrawalAmount())); //扣掉总金额
        userRoleInfoUpdateWrapper.set("update_time", DateUtil.getTime("yyyy-MM-dd HH:mm:ss"));
        int userRoleInfoNum = userRoleInfoMapper.update(null, userRoleInfoUpdateWrapper);
        if(userRoleInfoNum < 1){
            return Result.error("提现申请失败(1)!");
        }

        //3.提现申请表添加一条数据
        int withdrawalReviewNum = withdrawalReviewMapper.insert(withdrawalReview);
        if(withdrawalReviewNum < 1){
            throw new RuntimeException("提现申请失败(2)!");
        }

        return Result.OK("提现申请成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> jsWithdrawalReject(String id) {
        //1.获取提现申请表数据
        QueryWrapper<WithdrawalReview> withdrawalReviewQueryWrapper = new QueryWrapper<>();
        withdrawalReviewQueryWrapper.eq("id", id);
        withdrawalReviewQueryWrapper.eq("review_status", WithdrawalReviewConstant.reviewStatus_wait);
        withdrawalReviewQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        WithdrawalReview withdrawalReview = withdrawalReviewMapper.selectOne(withdrawalReviewQueryWrapper);
        if(oConvertUtils.isNotEmpty(withdrawalReview)){
            //2.退回提现金额
            //先查看余额和总金额(行上锁)
            UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(withdrawalReview.getUserId(), withdrawalReview.getUserType());
            //回退金额
            UpdateWrapper<UserRoleInfo> userRoleInfoUpdateWrapper = new UpdateWrapper<>();
            userRoleInfoUpdateWrapper.eq("user_id", withdrawalReview.getUserId());
            userRoleInfoUpdateWrapper.eq("user_type", withdrawalReview.getUserType());
            userRoleInfoUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
            userRoleInfoUpdateWrapper.set("balance", userRoleInfo.getBalance().add(withdrawalReview.getWithdrawalAmount())); //余额，退回提现金额
            userRoleInfoUpdateWrapper.set("total_amount", userRoleInfo.getTotalAmount().add(withdrawalReview.getWithdrawalAmount())); //总金额，退回提现金额
            userRoleInfoUpdateWrapper.set("update_time", DateUtil.getTime("yyyy-MM-dd HH:mm:ss"));
            int userRoleInfoNum = userRoleInfoMapper.update(null, userRoleInfoUpdateWrapper);
            if(userRoleInfoNum < 1){
                return Result.error("提现申请驳回失败(1)!");
            }

            //3.提现申请变更为驳回
            UpdateWrapper<WithdrawalReview> withdrawalReviewUpdateWrapper = new UpdateWrapper<>();
            withdrawalReviewUpdateWrapper.eq("id", id);
            withdrawalReviewUpdateWrapper.eq("review_status", WithdrawalReviewConstant.reviewStatus_wait); //待审核
            withdrawalReviewUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
            withdrawalReviewUpdateWrapper.set("review_status", WithdrawalReviewConstant.reviewStatus_reject); //驳回
            withdrawalReviewUpdateWrapper.set("update_time", DateUtil.getTime("yyyy-MM-dd HH:mm:ss"));
            int withdrawalReviewNum = withdrawalReviewMapper.update(null, withdrawalReviewUpdateWrapper);
            if(withdrawalReviewNum < 1){
                throw new RuntimeException("提现申请驳回失败(2)!");
            }

            return Result.OK("提现申请驳回成功");
        }else{
            return Result.error("提现申请驳回失败，该提现申请数据不是待审核状态");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> jsWithdrawalPass(String id) {
        //1.获取提现申请表数据
        QueryWrapper<WithdrawalReview> withdrawalReviewQueryWrapper = new QueryWrapper<>();
        withdrawalReviewQueryWrapper.eq("id", id);
        withdrawalReviewQueryWrapper.eq("review_status", WithdrawalReviewConstant.reviewStatus_wait);
        withdrawalReviewQueryWrapper.eq("del_flag", DelFlagConstant.normal);
        WithdrawalReview withdrawalReview = withdrawalReviewMapper.selectOne(withdrawalReviewQueryWrapper);
        if(oConvertUtils.isNotEmpty(withdrawalReview)){
            //2.资金流水表添加一条提现数据
            //先查看余额(行上锁)
            UserRoleInfo userRoleInfo = userRoleInfoMapper.queryOneForUpdate(withdrawalReview.getUserId(), withdrawalReview.getUserType());
            //查询账号
            UserBasic userBasic =userBasicMapper.selectById(userRoleInfo.getUserId());
            //在资金流水增加一条数据
            CapitalFlow capitalFlow = new CapitalFlow();
            capitalFlow.setUserId(userRoleInfo.getUserId());
            capitalFlow.setAccount(userBasic.getAccount());
            capitalFlow.setUserType(userRoleInfo.getUserType());
            capitalFlow.setChangeType(CapitalFlowTypeConstant.withdrawal); //3-提现
            capitalFlow.setChangeName(CapitalFlowTypeConstant.withdrawalName); //提现
            capitalFlow.setBeforeChangeAmount(userRoleInfo.getBalance().add(withdrawalReview.getWithdrawalAmount()));
            capitalFlow.setChangeAmount(withdrawalReview.getWithdrawalAmount().negate());
            capitalFlow.setAfterChangeAmount(userRoleInfo.getBalance());
            capitalFlow.setUpOrDown(CapitalFlowTypeConstant.money_down);
            int capitalFlowNum = capitalFlowMapper.insert(capitalFlow);
            if(capitalFlowNum < 1){
                return Result.error("提现申请审核失败(1)!");
            }

            //3.提现申请变更为审核通过
            UpdateWrapper<WithdrawalReview> withdrawalReviewUpdateWrapper = new UpdateWrapper<>();
            withdrawalReviewUpdateWrapper.eq("id", id);
            withdrawalReviewUpdateWrapper.eq("review_status", WithdrawalReviewConstant.reviewStatus_wait); //待审核
            withdrawalReviewUpdateWrapper.eq("del_flag", DelFlagConstant.normal);
            withdrawalReviewUpdateWrapper.set("review_status", WithdrawalReviewConstant.reviewStatus_pass); //审核通过
            withdrawalReviewUpdateWrapper.set("update_time", DateUtil.getTime("yyyy-MM-dd HH:mm:ss"));
            int withdrawalReviewNum = withdrawalReviewMapper.update(null, withdrawalReviewUpdateWrapper);
            if(withdrawalReviewNum < 1){
                throw new RuntimeException("提现申请审核失败(2)!");
            }

            return Result.OK("提现申请审核成功");
        }else{
            return Result.error("提现申请审核失败，该提现申请数据不是待审核状态");
        }
    }


}
